package com.kx.kxblog.service.impl;

import com.kx.kxblog.dao.SiteDao;
import com.kx.kxblog.dao.UserDao;
import com.kx.kxblog.entity.Site;
import com.kx.kxblog.entity.User;
import com.kx.kxblog.entity.vo.UserLoginVO;
import com.kx.kxblog.entity.vo.UserRegisterVO;
import com.kx.kxblog.enums.ResultCode;
import com.kx.kxblog.enums.SystemContextKey;
import com.kx.kxblog.exception.ResultException;
import com.kx.kxblog.service.UserService;
import com.kx.kxblog.util.BeanUtils;
import com.kx.kxblog.util.SystemContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import javax.transaction.Transactional;

@Service
public class UserServiceImpl extends AbstractServiceImpl<User, Integer,UserDao> implements UserService {

    @Autowired
    private SiteDao siteDao;

    @Autowired
    public void setDao(UserDao dao){
        this.dao = dao;
    }

    @Override
    public User login(UserLoginVO loginVO) {
        User user = dao.findByUser(loginVO.getUser());
        if(user==null)
            throw new ResultException(ResultCode.DATA_NOT_EXISTS.getCode(), "用户不存在");
        if(!user.getPassword().equals(loginVO.getPassword()))
            throw new ResultException(ResultCode.PASSWORD_INCORRECT);
        HttpSession session = (HttpSession) SystemContext.get(SystemContextKey.SESSION);
        String token = session.getId();
//        user.setToken(token);
        SystemContext.put(SystemContextKey.USER, user);
        user = dao.save(user);
        return user;
    }

    @Override
    @Transactional
    public User register(UserRegisterVO registerVO) {
        User user = dao.findByUser(registerVO.getUser());
        if(user!=null)
            throw new ResultException(ResultCode.DATA_EXISTS.getCode(), "该用户名已被注册");
        user = BeanUtils.copyProperties(registerVO, new User());
        user = dao.save(user);

        Site site = new Site().setUserId(user.getId()).setTitle(user.getNickName());
        siteDao.save(site);
        return user;
    }
}
